package com.ruoyi.project.system.interact.controller;

import java.util.List;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.interact.domain.DjGraphicDynamic;
import com.ruoyi.project.system.interact.domain.DjGraphicComment;
import com.ruoyi.project.system.interact.service.IDjGraphicDynamicService;
import com.ruoyi.project.system.interact.service.IDjGraphicCommentService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.common.utils.security.ShiroUtils;

/**
 * 绘声绘影Controller
 * 
 * @author ruoyi
 * @date 2023-07-15
 */
@Controller
@RequestMapping("/hui/interact/graphic")
public class GraphicController extends BaseController
{
    private String prefix = "system/interact/graphic";

    @Autowired
    private IDjGraphicDynamicService djGraphicDynamicService;

    @Autowired
    private IDjGraphicCommentService djGraphicCommentService;

    /**
     * 跳转到绘声绘影页面
     */
    @RequiresPermissions("hui:interact:graphic:view")
    @GetMapping()
    public String graphic(ModelMap mmap)
    {
        // 获取当前登录用户信息并传递到模板
        mmap.put("user", getSysUser());
        return prefix + "/graphic";
    }

    /**
     * 查询绘声绘影动态列表
     */
    @RequiresPermissions("hui:interact:graphic:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DjGraphicDynamic djGraphicDynamic)
    {
        startPage();
        List<DjGraphicDynamic> list = djGraphicDynamicService.selectDjGraphicDynamicList(djGraphicDynamic);
        return getDataTable(list);
    }

    /**
     * 导出绘声绘影动态列表
     */
    @RequiresPermissions("hui:interact:graphic:export")
    @Log(title = "绘声绘影动态", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public void export(HttpServletResponse response, DjGraphicDynamic djGraphicDynamic)
    {
        List<DjGraphicDynamic> list = djGraphicDynamicService.selectDjGraphicDynamicList(djGraphicDynamic);
        ExcelUtil<DjGraphicDynamic> util = new ExcelUtil<DjGraphicDynamic>(DjGraphicDynamic.class);
        util.exportExcel(response, list, "绘声绘影动态数据");
    }

    /**
     * 新增绘声绘影动态
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        // 传递当前用户信息到新增页面
        mmap.put("currentUser", getSysUser());
        return prefix + "/add";
    }

    /**
     * 新增保存绘声绘影动态
     */
    @RequiresPermissions("hui:interact:graphic:add")
    @Log(title = "绘声绘影动态", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(
            @RequestParam("title") String title,
            @RequestParam("content") String content)
    {
        try {
            DjGraphicDynamic djGraphicDynamic = new DjGraphicDynamic();
            djGraphicDynamic.setTitle(title);
            djGraphicDynamic.setContent(content);
            // 自动获取当前登录用户信息
            djGraphicDynamic.setPublisher(ShiroUtils.getSysUser().getUserName());
            djGraphicDynamic.setAvatar(ShiroUtils.getSysUser().getAvatar());
            djGraphicDynamic.setCreateBy(ShiroUtils.getSysUser().getUserName());
            djGraphicDynamic.setCreateTime(new Date());
            djGraphicDynamic.setAuditFlag("0"); // 待审核状态
            
            return toAjax(djGraphicDynamicService.insertDjGraphicDynamic(djGraphicDynamic));
        } catch (Exception e) {
            return AjaxResult.error("发布动态失败：" + e.getMessage());
        }
    }

    /**
     * 修改绘声绘影动态
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        DjGraphicDynamic djGraphicDynamic = djGraphicDynamicService.selectDjGraphicDynamicById(id);
        // 传递当前用户信息到编辑页面
        mmap.put("currentUser", getSysUser());
        mmap.put("djGraphicDynamic", djGraphicDynamic);
        return prefix + "/edit";
    }

    /**
     * 修改保存绘声绘影动态
     */
    @RequiresPermissions("hui:interact:graphic:edit")
    @Log(title = "绘声绘影动态", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody DjGraphicDynamic djGraphicDynamic)
    {
        try {
            // 获取原动态信息
            DjGraphicDynamic existing = djGraphicDynamicService.selectDjGraphicDynamicById(djGraphicDynamic.getId());
            if (existing == null) {
                return AjaxResult.error("动态不存在");
            }
            
            // 保留原有的发布者信息，如果为空则使用当前登录用户信息
            if (existing.getPublisher() == null || existing.getPublisher().trim().isEmpty()) {
                djGraphicDynamic.setPublisher(ShiroUtils.getSysUser().getUserName());
                djGraphicDynamic.setAvatar(ShiroUtils.getSysUser().getAvatar());
            } else {
                djGraphicDynamic.setPublisher(existing.getPublisher());
                djGraphicDynamic.setAvatar(existing.getAvatar());
            }
            
            return toAjax(djGraphicDynamicService.updateDjGraphicDynamic(djGraphicDynamic));
        } catch (Exception e) {
            return AjaxResult.error("编辑动态失败：" + e.getMessage());
        }
    }

    /**
     * 删除绘声绘影动态
     */
    @RequiresPermissions("hui:interact:graphic:remove")
    @Log(title = "绘声绘影动态", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ResponseBody
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(djGraphicDynamicService.deleteDjGraphicDynamicByIds(ids));
    }

    /**
     * 删除绘声绘影动态（POST方式）
     */
    @RequiresPermissions("hui:interact:graphic:remove")
    @Log(title = "绘声绘影动态", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult removePost(@RequestParam("ids") String ids)
    {
        String[] idArray = ids.split(",");
        Long[] longIds = new Long[idArray.length];
        for (int i = 0; i < idArray.length; i++) {
            longIds[i] = Long.parseLong(idArray[i]);
        }
        return toAjax(djGraphicDynamicService.deleteDjGraphicDynamicByIds(longIds));
    }

    /**
     * 查询已审核通过的公开动态
     */
    @GetMapping("/public")
    @ResponseBody
    public AjaxResult getPublicDynamics()
    {
        try {
            List<DjGraphicDynamic> dynamics = djGraphicDynamicService.selectPublicDynamics();
            return AjaxResult.success(dynamics);
        } catch (Exception e) {
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查看动态详情
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap)
    {
        DjGraphicDynamic djGraphicDynamic = djGraphicDynamicService.selectDjGraphicDynamicById(id);
        if (djGraphicDynamic == null) {
            return "error/404";
        }
        // 增加浏览量
        djGraphicDynamicService.incrementViewCount(id);
        // 查询评论列表
        List<DjGraphicComment> comments = djGraphicCommentService.selectCommentsByDynamicId(id);
        mmap.put("djGraphicDynamic", djGraphicDynamic);
        mmap.put("comments", comments);
        return "system/interact/detail";
    }

    /**
     * 获取动态详情JSON数据
     */
    @GetMapping("/detail/data/{id}")
    @ResponseBody
    public AjaxResult getDetailData(@PathVariable("id") Long id)
    {
        try {
            DjGraphicDynamic djGraphicDynamic = djGraphicDynamicService.selectDjGraphicDynamicById(id);
            if (djGraphicDynamic == null) {
                return AjaxResult.error("动态不存在");
            }
            // 增加浏览量
            djGraphicDynamicService.incrementViewCount(id);
            return AjaxResult.success(djGraphicDynamic);
        } catch (Exception e) {
            return AjaxResult.error("获取详情失败：" + e.getMessage());
        }
    }

    /**
     * 审核动态
     */
    @RequiresPermissions("hui:interact:graphic:audit")
    @Log(title = "绘声绘影动态", businessType = BusinessType.UPDATE)
    @PostMapping("/audit")
    @ResponseBody
    public AjaxResult audit(@RequestParam("id") Long id, @RequestParam("auditFlag") Integer auditFlag)
    {
        return toAjax(djGraphicDynamicService.auditDynamic(id, auditFlag));
    }

    /**
     * 跳转评论管理页面
     */
    @RequiresPermissions("hui:interact:graphic:view")
    @GetMapping("/comments/{dynamicId}")
    public String comments(@PathVariable("dynamicId") Long dynamicId, ModelMap mmap)
    {
        // 查询动态信息
        DjGraphicDynamic dynamicInfo = djGraphicDynamicService.selectDjGraphicDynamicById(dynamicId);
        
        mmap.put("dynamicId", dynamicId);
        mmap.put("dynamicInfo", dynamicInfo);
        return prefix + "/comments";
    }

    /**
     * 查询评论列表数据
     */
    @RequiresPermissions("hui:interact:graphic:list")
    @PostMapping("/comments/list")
    @ResponseBody
    public TableDataInfo commentsList(DjGraphicComment djGraphicComment)
    {
        startPage();
        List<DjGraphicComment> comments = djGraphicCommentService.selectDjGraphicCommentList(djGraphicComment);
        return getDataTable(comments);
    }

    /**
     * 获取动态的评论列表（用于详情页面）
     */
    @PostMapping("/detail/comments/{dynamicId}")
    @ResponseBody
    public AjaxResult getDetailComments(@PathVariable("dynamicId") Long dynamicId)
    {
        try {
            List<DjGraphicComment> comments = djGraphicCommentService.selectCommentsByDynamicIdWithPermission(dynamicId);
            return AjaxResult.success(comments);
        } catch (Exception e) {
            return AjaxResult.error("获取评论失败：" + e.getMessage());
        }
    }

    /**
     * 添加评论
     */
    @Log(title = "绘声绘影评论", businessType = BusinessType.INSERT)
    @PostMapping("/comment/add")
    @ResponseBody
    public AjaxResult addComment(@RequestBody DjGraphicComment djGraphicComment)
    {
        try {
           
            // 验证动态是否存在
            DjGraphicDynamic dynamic = djGraphicDynamicService.selectDjGraphicDynamicById(djGraphicComment.getDynamicId());
            if (dynamic == null) {
                logger.error("动态不存在: dynamicId={}", djGraphicComment.getDynamicId());
                return AjaxResult.error("动态不存在");
            }
            
            // 设置评论者信息
            djGraphicComment.setUsername(ShiroUtils.getSysUser().getUserName());
            djGraphicComment.setCommentTime(new Date());
            djGraphicComment.setAuditFlag(0); // 默认待审核
            djGraphicComment.setDelFlag(0);
            
            logger.info("准备插入评论: {}", djGraphicComment);
            
            int result = djGraphicCommentService.insertDjGraphicComment(djGraphicComment);
            
            logger.info("评论插入结果: result={}, commentId={}", result, djGraphicComment.getId());
            
            if (result > 0) {
                return AjaxResult.success("评论发布成功，待审核后显示");
            } else {
                return AjaxResult.error("评论发布失败");
            }
        } catch (Exception e) {
            logger.error("评论发布异常", e);
            return AjaxResult.error("评论发布失败：" + e.getMessage());
        }
    }

    /**
     * 审核评论
     */
    @RequiresPermissions("hui:interact:graphic:audit")
    @Log(title = "绘声绘影评论", businessType = BusinessType.UPDATE)
    @PostMapping("/comment/audit/{id}/{auditFlag}")
    @ResponseBody
    public AjaxResult auditComment(@PathVariable("id") Long id, @PathVariable("auditFlag") Integer auditFlag)
    {
        return toAjax(djGraphicCommentService.auditComment(id, auditFlag));
    }

    /**
     * 删除评论
     */
    @RequiresPermissions("hui:interact:graphic:remove")
    @Log(title = "绘声绘影评论", businessType = BusinessType.DELETE)
    @PostMapping("/comment/remove")
    @ResponseBody
    public AjaxResult removeComment(@RequestParam Long[] ids)
    {
        return toAjax(djGraphicCommentService.deleteDjGraphicCommentByIds(ids));
    }

    /**
     * 批量审核评论
     */
    @RequiresPermissions("hui:interact:graphic:audit")
    @Log(title = "绘声绘影评论", businessType = BusinessType.UPDATE)
    @PostMapping("/comment/batchAudit")
    @ResponseBody
    public AjaxResult batchAuditComment(@RequestParam("ids") String ids, @RequestParam("auditFlag") Integer auditFlag)
    {
        String[] idArray = ids.split(",");
        Long[] longIds = new Long[idArray.length];
        for (int i = 0; i < idArray.length; i++) {
            longIds[i] = Long.parseLong(idArray[i]);
        }
        return toAjax(djGraphicCommentService.batchAuditComments(longIds, auditFlag));
    }

    /**
     * 查询公开的已审核通过的动态列表（无需权限）
     */
    @PostMapping("/public/list")
    @ResponseBody
    public TableDataInfo publicList(DjGraphicDynamic djGraphicDynamic)
    {
        startPage();
        List<DjGraphicDynamic> list = djGraphicDynamicService.selectPublicDynamics();
        return getDataTable(list);
    }

    /**
     * 查看公开动态详情（无需权限）
     */
    @GetMapping("/public/detail/{id}")
    @ResponseBody
    public AjaxResult publicDetail(@PathVariable("id") Long id)
    {
        try {
            DjGraphicDynamic djGraphicDynamic = djGraphicDynamicService.selectDjGraphicDynamicById(id);
            if (djGraphicDynamic == null || !"1".equals(djGraphicDynamic.getAuditFlag())) {
                return AjaxResult.error("动态不存在或未审核通过");
            }
            // 增加浏览量
            djGraphicDynamicService.incrementViewCount(id);
            return AjaxResult.success(djGraphicDynamic);
        } catch (Exception e) {
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }
}